<template>
  <div class="createPost-container">
    <el-steps class="steps" :active="active" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="详细信息"></el-step>
      <el-step title="经费"></el-step>
      <el-step title="时间表"></el-step>
    </el-steps>
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <div class="createPost-main-container">
        <div v-show="active == 1">
          <div>
            <el-row gutter="80">
              <el-col :span="12">
                <div class="postInfo-container">
                  <el-row>
                    <el-form-item
                      prop="projectId"
                      label-width="180px"
                      label="项目编号："
                    >
                      <el-input
                        v-model="postForm.projectId"
                        :maxlength="100"
                        name="name"
                        disabled
                        placeholder="请输入项目编号"
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      prop="projectName"
                      label-width="180px"
                      label="项目名称："
                    >
                      <el-input
                        v-model="postForm.projectName"
                        :maxlength="100"
                        name="name"
                        placeholder="请输入项目名称"
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                  <el-form-item
                    prop="projectGroup"
                    label-width="180px"
                    label="所属课题组："
                  >
                    <el-select
                      v-model="postForm.projectGroupId"
                      :remote-method="getGroupList"
                      filterable
                      remote
                      placeholder="请选择课题组"
                      :loading="loading"
                      @change="changeGroup"
                    >
                      <el-option
                        v-for="item in groupListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item
                      label-width="180px"
                      label="项目所属部门："
                      prop="projectDepartment"
                    >
                      <el-input
                        v-model="postForm.projectDepartment"
                        :maxlength="100"
                        name="name"
                        disabled
                        placeholder="请输入所属部门"
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                <el-row>
                    <el-form-item
                      prop="projectStatus"
                      label-width="180px"
                      label="项目状态："
                    >
                      <el-input
                        v-model="postForm.projectStatus"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                </div>
              </el-col>

              <el-col :span="12">
                <el-row>
                  <el-form-item
                    prop="projectOwnerName"
                    label-width="180px"
                    label="课题组负责人："
                  >
                    <el-input
                      v-model="postForm.projectOwnerName"
                      :maxlength="100"
                      name="name"
                      disabled
                      placeholder="请输入课题组负责人"
                    >
                    </el-input>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item
                    prop="projectOwnerPhone"
                    label-width="180px"
                    label="负责人电话："
                  >
                    <el-input
                      v-model="postForm.projectOwnerPhone"
                      :maxlength="100"
                      name="name"
                      disabled
                      placeholder="请输入负责人电话"
                    >
                    </el-input>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item
                    prop="projectOwnerEmail"
                    label-width="180px"
                    label="负责人邮箱："
                  >
                    <el-input
                      v-model="postForm.projectOwnerEmail"
                      :maxlength="100"
                      name="name"
                      disabled
                      placeholder="请输入负责人邮箱"
                    >
                    </el-input>
                  </el-form-item>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </div>
        <div v-show="active == 2">
          <div>
            <el-row gutter="80">
              <el-col :span="12">
                <div class="postInfo-container">
                  <el-row>
                    <el-form-item
                      label-width="180px"
                      label="项目来源："
                      prop="projectSource"
                    >
                      <el-select
                        disabled
                        v-model="postForm.projectSource"
                        :remote-method="getSourceList"
                        filterable
                        remote
                        placeholder="请选择项目来源"
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in sourceListOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      label-width="180px"
                      label="项目研究类别："
                      prop="projectCategory"
                    >
                      <el-select
                        v-model="postForm.projectCategory"
                        :remote-method="getCategoryList"
                        filterable
                        remote
                        placeholder="请选择项目研究类别"
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in categoryListOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      label-width="180px"
                      label="项目级别："
                      prop="projectLevel"
                    >
                      <el-select
                        disabled
                        v-model="postForm.projectLevel"
                        :remote-method="getLevelList"
                        filterable
                        remote
                        placeholder="请选择项目级别"
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in levelListOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      label-width="180px"
                      label="成果形式："
                      prop="projectResultForm"
                    >
                      <el-input
                        v-model.number="postForm.projectResultForm"
                        class="article-textarea"
                        placeholder="请输入成果形式"
                      />
                    </el-form-item>
                  </el-row>
                      <el-row>
                        <el-form-item
                          label-width="180px"
                          label="上传附件："
                          prop="projectAttachFileUrl"
                        >
                          <el-upload
                            action="http://localhost:3001/api/projects/upload"
                            :limit="1"
                            :on-preview="handlePreview"
                            :before-remove="beforeRemove"
                            :on-exceed="handleExceed"
                            :on-success="handleSuccess"
                            :file-list="projectFileList"
                          >
                            <el-button size="small" type="primary"
                              >点击上传</el-button
                            >
                            <div slot="tip" class="el-upload__tip">
                              .docs 文件小于500kb
                            </div>
                          </el-upload>
                        </el-form-item>
                      </el-row>
                </div>
              </el-col>
              <el-col :span="12">
                <el-row>
                  <el-form-item
                    style="margin-bottom: 40px"
                    label-width="180px"
                    label="项目研究方向："
                    prop="projectDirection"
                    required
                  >
                    <el-input
                      v-model.number="postForm.projectDirection"
                      class="article-textarea"
                      placeholder="请输入研究方向"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item
                    style="margin-bottom: 40px"
                    label-width="180px"
                    label="项目主要研究内容："
                  >
                    <el-input
                      v-model="postForm.projectResearchDirection"
                      type="textarea"
                      class=""
                      :autosize="{ minRows: 4, maxRows: 8 }"
                      placeholder="请输入主要研究内容"
                    />
                  </el-form-item>
                </el-row>
<!--                <el-row>-->
<!--                  <el-form-item-->
<!--                    label-width="180px"-->
<!--                    label="项目统计年度："-->
<!--                    class="postInfo-container-item"-->
<!--                    prop="projectStatisticalYear"-->
<!--                  >-->
<!--                  <el-date-picker-->
<!--                    v-model="postForm.projectStatisticalYear"-->
<!--                    type="year"-->
<!--                    value-format="yyyy"-->
<!--                    placeholder="选择项目统计年度"-->
<!--                    disabled-->
<!--                  >-->
<!--                  </el-date-picker>-->
<!--                  </el-form-item>-->
<!--                </el-row>-->
              </el-col>
            </el-row>
          </div>
        </div>
        <div v-show="active == 3">
          <el-row>
            <el-form-item
              label-width="230px"
              label="项目申请经费分项："
              class="postInfo-container-item"
              prop="projectAppliedCostItems"
            >
              <el-table
                class="appropriation-table"
                :data="postForm.projectAppliedCostItems"
                border
              >
                <el-table-column label="经费预算科目" width="300px" align="center">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.id"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="金额（万元）" align="center">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.appropriation"
                      :maxlength="100"
                      name="name"
                      type="number"
                      @change="computedMoney"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column width="200px" align="center">
                  <template slot-scope="scope">
                    <div class="block float-right">
                      <el-button
                        v-loading="loading"
                        round
                        @click="removeItem(scope.row.index)"
                        icon="delete"
                      >
                        删除
                      </el-button>
                      <el-button
                        v-loading="loading"
                        round
                        v-if="
                          scope.$index + 1 ===
                          postForm.projectAppliedCostItems.length
                        "
                        @click="addItem(scope.$index)"
                      >
                        添加
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
                style="margin-bottom: 40px"
                prop="projectAppliedCostSource"
                label-width="230px"
                label="经费来源："
            >
              <el-input
                  v-model="postForm.projectAppliedCostSource"
                  :maxlength="100"
                  name="name"
                  placeholder="如自筹，医院，市……"
              >
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              style="margin-bottom: 40px"
              prop="projectAppliedCost"
              label-width="230px"
              label="项目申请经费总额（万元）："
            >
              <el-input
                v-model="postForm.projectAppliedCost"
                :maxlength="100"
                name="name"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              style="margin-bottom: 40px"
              prop="projectApprovedCost"
              label-width="230px"
              label="项目批准经费："
            >
              <el-input
                v-model="postForm.projectApprovedCost"
                :maxlength="100"
                name="name"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-row>
        </div>
        <div v-show="active == 4">
          <el-row>
            <el-form-item
              style="margin-bottom: 40px"
              prop="projectDeclareDate"
              label-width="180px"
              label="项目申请日期："
              required
            >
            <el-date-picker
                v-model="postForm.projectDeclareDate"
                type="date"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              style="margin-bottom: 40px"
              prop="projectCreatedDate"
              label-width="180px"
              label="项目立项日期："
            >
              <el-date-picker
                v-model="postForm.projectCreatedDate"
                type="date"
                placeholder="请选择立项日期"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-row>
<!--          <el-row>-->
<!--            <el-form-item-->
<!--              style="margin-bottom: 40px"-->
<!--              prop="projectStartDate"-->
<!--              label-width="180px"-->
<!--              label="项目开始日期："-->
<!--              required-->
<!--            >-->
<!--              <el-date-picker-->
<!--                v-model="postForm.projectStartDate"-->
<!--                type="date"-->
<!--                placeholder="请选择开始日期"-->
<!--              >-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-row>-->
<!--          <el-row>-->
<!--            <el-form-item-->
<!--              style="margin-bottom: 40px"-->
<!--              prop="projectExpectedEndDate"-->
<!--              label-width="180px"-->
<!--              label="项目计划结项日期："-->
<!--              required-->
<!--            >-->
<!--              <el-date-picker-->
<!--                v-model="postForm.projectExpectedEndDate"-->
<!--                type="date"-->
<!--                placeholder="请选择计划结项日期"-->
<!--              >-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-row>-->
          <el-row>
            <el-form-item
              style="margin-bottom: 40px"
              prop="projectEndDate"
              label-width="180px"
              label="项目实际结项日期："
            >
              <el-date-picker
                v-model="postForm.projectEndDate"
                type="date"
                placeholder="实际结项日期"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-row>
        </div>
      </div>
    </el-form>

    <div style="margin-top: 40px; margin-left: 230px">
      <el-button v-if="active > 1" style="width: 120px" @click="pre" type="primary"
        >上一步</el-button
      >
      <el-button v-if="active < 4" style="width: 120px" @click="next" type="primary"
        >下一步</el-button
      >
      <el-button
        v-loading="loading"
        style="width: 120px"
        type="primary"
        @click="submitForm"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
import sourceList from "@/data/projectSources";
import categoryList from "@/data/researchCategories";
import levelList from "@/data/projectLevels";
import { fetchApprovedAppropriationList } from "@/api/appropriation";
import { fetchProjectId, fetchProjectById, createProject, updateProject } from "@/api/project";
import { fetchResearchGroupList } from "@/api/research-group";
import { generateNewDate } from '@/utils/date';
import { mapGetters } from "vuex";
import {fetchProjectDeclareById} from "@/api/project-declare";

const defaultForm = {
  projectId: "", // 项目编号
  projectName: "", // 项目名称
  projectDeclareId: null,// 项目申报题目id
  projectDeclareName: "", // 项目申报题目
  projectGroupId: null, // 课题组id
  projectGroupName: "", // 课题组名称
  projectOwnerId: null, // 项目负责人ID
  projectOwnerEmployeeId: "", // 项目负责人编号
  projectOwnerName: "", // 项目负责人名字
  projectOwnerPhone: "", // 项目负责人电话
  projectOwnerEmail: "", // 项目负责人邮箱
  projectDepartment: "", // 项目所属部门
  projectSource: "",
  projectCategory: "",
  projectLevel: "",
  projectDirection: "",
  projectResearchDirection: "",
  projectStatus: "项目未立项", // 项目状态
  projectDeclareDate: null,
  projectCreatedDate: null,
  projectStartDate: null,
  projectExpectedEndDate: null,
  projectEndDate: null,
  projectApprovedCost: null, // 项目已批准经费
  projectAppliedCost: null,
  projectAppliedCostSource: "", // 项目经费来源
  projectAppliedCostItems: [],
  projectResultForm: "",
  projectStatisticalYear: null, // 项目统计年度
  projectAttachFileName: "", // 项目立项报告名字
  projectAttachFileUrl: "", // 项目立项报告地址
  projectChangeReport: "", // 项目变更证明材料
  projectChangeReportName: "", // 项目变更证明材料名称
  projectChangeDescription: "", // 项目变更说明
  projectEthicalApproverId1: null,
  projectEthicalApproverName1: "",
  projectEthicalApproverId2: null,
  projectEthicalApproverName2: "",
  projectCostApproverId: null,
  projectCostApproverName: "",
  projectPreApproverId: null,
  projectPreApproverName: "",
  projectEndApproverId: null,
  projectEndApproverName: "",
  projectSubjectReport: "", // 项目中检报告
  projectSubjectReportName: '', // 项目中检文件名
  projectSubjectDate: null, // 项目中检日期
  projectSubjectDescription: "", // 项目中检说明
  projectSubjectApproverId: null, // 项目中检者ID
  projectSubjectApproverName: "", // 项目中检者名字
  projectMidReportName: "", // 项目中检文件名
  projectMidReport: "", // 项目中检报告
  projectMidDate: null, // 项目中检日期
  projectMidDescription: "", // 项目中检说明
  projectFinalReportName: "", // 项目结项文件名
  projectFinalReport: "", // 项目结项报告
  projectFinalDate: null, // 项目结项日期
  projectFinalDescription: "", // 项目结项说明
  projectMidApproverId: null, // 项目中检者ID
  projectMidApproverName: "", // 项目中检者名字
  projectFinalApproverId: null, // 项目结项者ID
  projectFinalApproverName: "", // 项目结项者名字
  projectCheckStatus: "提交项目开题报告", // 项目审批状态
  projectCheckHistory: null, // 项目审批履历
  projectChangeHistory: null,
  projectApplicantId: null,
  projectApplicantName: "",
  projectInformationCheckStatus: "科研处立项预审中", // 项目信息审核状态
  projectInformationCheckHistory: null,
  projectChangeStatus: null, // 项目变更状态
  projectEthicCheckCount: 0, // 伦理审批通过个数
  id: undefined,
};

export default {
  name: "ProjectDetail",
  props: {
    isCreate: {
      type: Boolean,
      default: true,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (!value || value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      active: 1,
      appropriationList: [],
      appropriationListOptions: [],
      groupList: [],
      groupListOptions: [],
      categoryListOptions: categoryList,
      sourceListOptions: sourceList,
      levelListOptions: levelList,
      fileList: [],
      projectFileList: [],
      rules: {
        projectName: [{ required: true, validator: validateRequire }],
        projectGroupId: [{ required: true, validator: validateRequire }],
        projectOwnerPhone: [{ required: true, validator: validateRequire }],
        projectDepartment: [{ required: true, validator: validateRequire }],
        projectSource: [{ required: true, validator: validateRequire }],
        projectCategory: [{ required: true, validator: validateRequire }],
        projectLevel: [{ required: true, validator: validateRequire }],
        projectDirection: [{ required: true, validator: validateRequire }],
        projectStatus: [{ required: true, validator: validateRequire }],
        projectAppliedCostItems: [
          { required: true, validator: validateRequire },
        ],
        // projectStartDate: [{ required: true, validator: validateRequire }],
        // projectExpectedEndDate: [
        //   { required: true, validator: validateRequire },
        // ],
        projectAttachFileUrl: [{ required: true, validator: validateRequire }],
      },
    };
  },
  created() {
    this.getProjectId();
    this.getAppropriations();
    this.getGroups();
    this.getDeclare()

    if (this.isEdit) {
      const projectId = this.$route.params && this.$route.params.id;
      this.fetchData(projectId);
    } else {
      if(this.isCreate && this.$route.params && this.$route.params.id) {
      this.postForm.projectAppliedCostItems = [{
      index: 0,
      id: null,
      name: null,
      appropriation: null,
      startDate: null,
      endDate: null,
    }];
    this.postForm.projectDeclareDate = generateNewDate();
      this.postForm.projectDeclareId = parseInt(this.$route.params.id);
      this.postForm.projectDeclareName = this.$route.params.title;
    }
  }
  },
  computed: {
    ...mapGetters(["id", "name", "roles"])
  },
  methods: {
    computedMoney() {
      this.postForm.projectAppliedCost = this.postForm.projectAppliedCostItems.reduce(
        (acc, cur) => {
          return acc + Number(cur.appropriation);
        },
        0
      );
    },
    getDeclare() {
      fetchProjectDeclareById(this.$route.params.id)
        .then((res) => {
          this.postForm.projectLevel = res.data[0].projectLevel;
          this.postForm.projectSource = res.data[0].projectSource;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getProjectId() {
      fetchProjectId().then((res) => {
        this.postForm.projectId = res.data;
      });
    },
    next() {
      if (this.active++ > 4) this.active = 1;
    },
    pre() {
      if (this.active-- < 2) this.active = 1;
    },
    handlePreview(file) {
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.download = file.name;
      a.href = file.response? `http://localhost:3001/${file.response.srcurl}` : file.url;
      a.dispatchEvent(event);
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `文件数量限制为1, 您选择了 ${files.length} 个文件。`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`删除 ${file.name} ?`);
    },
    async handleSuccess(res, file) {
      if (res.status === "1") return this.$message.error(res.message);
        this.postForm.projectAttachFileUrl = `http://localhost:3001/${res.srcurl}`;
        this.postForm.projectAttachFileName = file.name;
    },
    getAppropriations() {
      this.listLoading = true;
      fetchApprovedAppropriationList().then((res) => {
        this.appropriationList = res.data.map((item) => {
          return {
            label: item.appropriationName,
            value: item.id,
            appropriation: item.appropriationStandard,
            startDate: item.appropriationStart,
            endDate: item.appropriationEnd,
          };
        });
        this.appropriationListOptions = this.appropriationList;

        this.listLoading = false;
      });
    },
    getGroups() {
      this.listLoading = true;
      fetchResearchGroupList().then((res) => {
        let emptyList = res.data.filter((item) =>  !item.project_id);
        if (this.postForm.id) {
          const ownerList = res.data.filter(item => item.project_id === this.postForm.id);
          emptyList = [...ownerList,...emptyList]
        }
        this.groupList = emptyList.map((item) => {

          return {
            label: item.researchGroupName,
            value: item.id,
            ownerName: item.researchGroupOwnerName,
            ownerId: item.researchGroupOwnerId,
            ownerEmployeeId: item.researchGroupOwnerEmployeeId,
            phone: item.researchGroupOwnerPhone,
            email: item.researchGroupOwnerEmail,
            department: item.researchGroupDepartment
          };
        });
        this.groupListOptions = this.groupList;
        this.listLoading = false;
      });
    },
    getSourceList(query) {
      if (query !== "") {
        this.loading = true;
        this.sourceListOptions = sourceList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.sourceListOptions = sourceList;
      }
    },
    getCategoryList(query) {
      if (query !== "") {
        this.loading = true;
        this.categoryListOptions = categoryList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.categoryListOptions = categoryList;
      }
    },
    getLevelList(query) {
      if (query !== "") {
        this.loading = true;
        this.levelListOptions = levelList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.levelListOptions = levelList;
      }
    },
    getGroupList(query) {
      if (query !== "") {
        this.loading = true;
        this.groupListOptions = groupList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.groupListOptions = groupList;
      }
    },
    addItem(val) {
      console.log(`dsfdsfsf${val}`)
      let checkEmptyItems = this.postForm.projectAppliedCostItems.filter(
        (item) => item.appropriation === null
      );
      if (
        checkEmptyItems.length >= 1 &&
        this.postForm.projectAppliedCostItems.length > 0
      ) {
        this.$message({
          message: "费用信息不能为空",
          type: "error",
        });
        return;
      }
      this.postForm.projectAppliedCostItems.push({
        index: val + 1,
        id: null,
        name: null,
        appropriation: null,
        startDate: null,
        endDate: null,
      });
    },
    removeItem(itemIndex) {
      console.log(`remove${itemIndex}`)
      if (this.postForm.projectAppliedCostItems.length > 1) {
        this.postForm.projectAppliedCostItems.splice(itemIndex, 1);
      } else {
        this.postForm.projectAppliedCostItems = [{
        index: 0,
        id: null,
        name: null,
        appropriation: null,
        startDate: null,
        endDate: null,
      }];
      }
      this.caculateTotalCost();
    },
    changeGroup(val) {
      const selectedItem = this.groupList.find((item) => {
        return item.value === val;
      });
      this.postForm.projectGroupId = selectedItem.value;
      this.postForm.projectGroupName = selectedItem.label;
      this.postForm.projectOwnerId = selectedItem.ownerId;
      this.postForm.projectOwnerEmployeeId = selectedItem.ownerEmployeeId;
      this.postForm.projectOwnerName = selectedItem.ownerName;
      this.postForm.projectOwnerPhone = selectedItem.phone;
      this.postForm.projectOwnerEmail = selectedItem.email;
      this.postForm.projectDepartment = selectedItem.department;
    },
    caculateTotalCost() {
      let totalCost = 0;

      this.postForm.projectAppliedCostItems.forEach((item) => {
        totalCost += item.appropriation ? item.appropriation : 0;
      });
      this.postForm.projectAppliedCost = totalCost;
    },
    changeAppropriation(val) {
      const selectedItem = this.appropriationList.find((item) => {
        return item.value === val.id;
      });
      for (const item of this.postForm.projectAppliedCostItems) {
        if (item.id === val.id) {
          item.name = selectedItem.label;
          item.appropriation = selectedItem.appropriation;
          item.startDate = selectedItem.startDate;
          item.endDate = selectedItem.endDate;
          break;
        }
      }
      this.caculateTotalCost();
    },
    fetchData(id) {
      fetchProjectById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.fileList = this.postForm.projectChangeReportName
            ? (this.fileList = [
                {
                  name: this.postForm.projectChangeReportName,
                  url: this.postForm.projectChangeReport,
                },
              ])
            : [];
          this.postForm.projectAppliedCostItems =
            this.postForm.projectAppliedCostItems?.length > 0
              ? JSON.parse(this.postForm.projectAppliedCostItems)
              : [];
          this.projectFileList = this.projectCheck.projectAttachFileName
              ? [
                  {
                    name: this.projectCheck.projectAttachFileName,
                    url: this.projectCheck.projectAttachFileUrl,
                  },
                ]
              : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.postForm.projectAppliedCostItems =
            this.postForm.projectAppliedCostItems.filter((item) => {
              return item && item.id
            });
          if (!this.isEdit) {
            this.postForm.projectApplicantId = this.id;
            this.postForm.projectApplicantName = this.name;
            createProject(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/project/list");

                  this.$message({
                    title: "成功",
                    message: "项目创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "项目创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            updateProject(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  if (this.isEthic || this.isApprove || this.isCost) {
                    this.$router.push("/approve/list");
                  } else {
                    this.$router.push("/project/list");
                  }
                  this.$message({
                    title: "成功",
                    message: "项目信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "项目信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("项目信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .steps {
    margin: 50px 0 30px 0;
  }

  .file-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .file-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}
</style>
